const router = require('koa-router')()
const fs = require('fs')
/*
  公共管理接口
*/
router

// 更新网站基本信息 ↓
.post('/updateWebsiteInfo', async (ctx, next) => {
  let query = ctx.request.body
  console.log(query)
  if (query._id == undefined) {
    try {
      let result = await ctx.db.WebsiteInfo.create({
        ...query
      })
      ctx.body = {
        code: 0,
        message: '成功创建新的网站信息',
        data: result
      }
    } catch (error) {
      console.log(error.message)
      ctx.body = { code: 1, message: error.message, data: null }
    }
  }
  try {
    let result = await ctx.db.WebsiteInfo.updateOne({_id: query._id},{
      zhName: query.zhName,
      engName: query.engName,
      iconUrl: query.iconUrl,
      master: query.master
    })
    
    ctx.body = {
      code: 0,
      message: '更新成功',
      data: result
    }
  } catch (error) {
    console.log(error.message)
    ctx.body = {
      code: 1,
      message: error.message,
      data: null
    }
  }
})

// 获取密钥 ↓
.get('/getSecretKey', async (ctx, next) => {
  let rgisterKey,tokenKey
  try {
    rgisterKey = fs.readFileSync('./assets/key/register.key', 'utf-8')
    tokenKey = fs.readFileSync('./assets/key/tokenKey.key', 'utf-8') 
    if(!!rgisterKey && !!tokenKey) {
      ctx.body = {
        code: 0,
        message: '成功获取SecretKey',
        data: {
          registerKey: rgisterKey,
          tokenKey: tokenKey
        }
      }
    }
  } catch (error) { 
    console.log(error)
    ctx.body = {
      code: 0,
      message: '成功获取SecretKey',
      data: {
        registerKey: rgisterKey,
        tokenKey: tokenKey
      }
    }
  }
})

// 设置密钥 ↓
.post('/editSecretKey', async (ctx, next) => {
  const query = ctx.request.body
  console.log(query)
  try {
    if(query.type == 0) {
      fs.writeFileSync('./assets/key/register.key', query.key, 'utf-8')
      ctx.body = { code: 0, message: '注册密钥修改成功', data: null }
    }
    else {
      fs.writeFileSync('./assets/key/tokenKey.key', query.key, 'utf-8')
      ctx.body = { code: 0, message: '登录密钥修改成功', data: null }
    }
  } catch (error) { 
    console.log(error)
    ctx.body = { code: 1, message: '成功获取SecretKey', data: null }
  }
})


// 轮播管理

// 添加轮播图
.post('/setSlidesShow', async (ctx, next) => {
  let query = ctx.request.body
  try {
    let res = await ctx.db.SlidesShow.create({
      ...query
    })
    ctx.body = { code: 0, message: '添加成功', data: res }
  } catch (error) {
    console.log(error.message)
    ctx.body = { code: 1, message: error.message, data: null }
  }
})
// 删除轮播图
.post('/deleteSlidesShow', async (ctx, next) => {
  let query = ctx.request.body
  try {
    let res = await ctx.db.SlidesShow.deleteOne({
      _id: query.id
    })
    ctx.body = { code: 0, message: '删除成功', data: res }
  } catch (error) {
    console.log(error.message)
    ctx.body = { code: 1, message: error.message, data: null }
  }
})



module.exports = router
